package com.jiangjiang.eshop.purchase.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangjiang.eshop.purchase.convert.PurchaseOrderItemConvert;
import com.jiangjiang.eshop.purchase.dao.PurchaseOrderItemMapper;
import com.jiangjiang.eshop.purchase.domain.PurchaseOrderItemEntity;
import com.jiangjiang.eshop.purchase.dto.PurchaseOrderItemDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName PurchaseOrderItemService
 * @Description TODO
 * @Author jhw
 * @Date 2021/9/20 7:34
 * @Version 1.0
 **/
@Service
public class PurchaseOrderItemService extends ServiceImpl<PurchaseOrderItemMapper, PurchaseOrderItemEntity> {

    @Autowired
    private PurchaseOrderItemConvert purchaseOrderItemConvert;

    /**
     * 保存采购单条目数据
     * @param purchaseOrderId 采购单id
     * @param purchaseOrderItemDTOList 采购单条目数据
     */
    public void savePurchaseOrderItems(Long purchaseOrderId, List<PurchaseOrderItemDTO> purchaseOrderItemDTOList) {
        List<PurchaseOrderItemDTO> itemsList = purchaseOrderItemDTOList.stream()
                .peek(itemDTO -> itemDTO.setPurchaseOrderId(purchaseOrderId))
                .collect(Collectors.toList());

        this.saveBatch(purchaseOrderItemConvert.convertDTOList2Entities(itemsList));
    }

    /**
     * 采购明细数据删除
     * @param purchaseOrderId 采购单id
     */
    public void removeByPurchaseOrderId(Long purchaseOrderId) {
        LambdaQueryWrapper<PurchaseOrderItemEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PurchaseOrderItemEntity::getPurchaseOrderId, purchaseOrderId);
        this.remove(wrapper);
    }

    /**
     * 根据采购单id查询采购单明细数据
     * @param purchaseOrderId 采购单id
     * @return 查询结果
     */
    public List<PurchaseOrderItemDTO> queryByPurchaseOrderId(Long purchaseOrderId) {
        LambdaQueryWrapper<PurchaseOrderItemEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PurchaseOrderItemEntity::getPurchaseOrderId, purchaseOrderId);
        return purchaseOrderItemConvert.convertEntity2DTO(this.list(wrapper));
    }

}
